package xmu.zfw.controller;


import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import xmu.zfw.config.ExcelTypeConf;
import xmu.zfw.domain.Report;
import xmu.zfw.mapper.ReportMapper;
import xmu.zfw.service.ReportService;
import xmu.zfw.util.ExcelImporter;
import xmu.zfw.util.ResponseUtil;
import xmu.zfw.vo.ReportVO;
import xmu.zfw.vo.SearchReportVO;


import javax.servlet.http.HttpServletResponse;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.sql.Date;
import java.util.ArrayList;
import java.util.List;

@RestController
@CrossOrigin
public class ReportController {

    @Autowired
    private ReportService reportService;

    @Autowired
    private ReportMapper reportMapper;

    @ApiOperation("Ready, 查询全部报告或者按照报告类别(reportType)查询报告")
    @GetMapping("/report")
    public Object getAll(@RequestParam(value = "type", defaultValue = "null") String reportType,
                         @RequestParam(value = "page_index", defaultValue = "1") Integer pageIndex,
                         @RequestParam(value = "page_size", defaultValue = "10") Integer pageSize){
        PageHelper.startPage(pageIndex, pageSize);
        List<Report> reportList;
        List<ReportVO> reportVOList;
        if(reportType.equals("null")){
            reportList = reportService.getAll();
        }else{
            reportList = reportService.getReportsByReportType(reportType);
        }

        if(reportList == null){
            return ResponseUtil.fail();
        }else{
            reportVOList = ReportVO.getReportVOs(reportList);

            PageInfo pageInfo = ((Page)reportList).toPageInfo();
            pageInfo.setList(reportVOList);

            return ResponseUtil.ok(pageInfo);
        }
    }

    @ApiOperation("Ready, 查询全部报告或者按照报告类别(reportType)查询报告")
    @GetMapping("/report/all")
    public Object getAllData(){
        List<Report> reportList = reportService.getAll();
        List<ReportVO> reportVOList = ReportVO.getReportVOs(reportList);
        return ResponseUtil.ok(reportVOList);
    }

    @ApiOperation("Ready, check 未查结 and isSend 已移送、未移送")
    @GetMapping("/report/send")
    public Object getAllBySend(@RequestParam(value = "isSend") String isSend,
                               @RequestParam(value = "page_index", defaultValue = "1") Integer pageIndex,
                               @RequestParam(value = "page_size", defaultValue = "10") Integer pageSize){
        PageHelper.startPage(pageIndex, pageSize);
        List<Report> reportList;
        List<ReportVO> reportVOList;
        reportList = reportService.getTodoReportsByIsSend(isSend);
        if(reportList == null){
            return ResponseUtil.fail();
        }else {
            reportVOList = ReportVO.getReportVOs(reportList);

            PageInfo pageInfo = ((Page)reportList).toPageInfo();
            pageInfo.setList(reportVOList);

            return ResponseUtil.ok(pageInfo);
        }
    }

    @ApiOperation("Ready, check progress 查结")
    @GetMapping("/report/progress")
    public Object getAllByProgress(@RequestParam(value = "progress") String progress,
                               @RequestParam(value = "page_index", defaultValue = "1") Integer pageIndex,
                               @RequestParam(value = "page_size", defaultValue = "10") Integer pageSize){
        PageHelper.startPage(pageIndex, pageSize);
        List<Report> reportList;
        List<ReportVO> reportVOList;

        reportList = reportService.getReportsByProgress(progress);
        if(reportList == null){
            return ResponseUtil.fail();
        }else {

            reportVOList = ReportVO.getReportVOs(reportList);
            PageInfo<ReportVO> pageInfo = new PageInfo<>(reportVOList);
            return ResponseUtil.ok(pageInfo);
        }

    }
    @ApiOperation("Ready, check progress 未查结 and feedbackTime<today")
    @GetMapping("/report/timeout")
    public Object getAllTimeout(@RequestParam(value = "page_index", defaultValue = "1") Integer pageIndex,
                                   @RequestParam(value = "page_size", defaultValue = "10") Integer pageSize){
        PageHelper.startPage(pageIndex, pageSize);
        List<Report> reportList;
        List<ReportVO> reportVOList;
        reportList = reportService.getAllTimeout();
        if(reportList == null){
            return ResponseUtil.fail();
        }else {
            reportVOList = ReportVO.getReportVOs(reportList);

            PageInfo pageInfo = ((Page)reportList).toPageInfo();
            pageInfo.setList(reportVOList);
            return ResponseUtil.ok(pageInfo);
        }

    }

    @ApiOperation("Ready, 查询紧急报告")
    @GetMapping("/report/urgent")
    public Object searchUrgentReports(
            @RequestParam(value = "page_index", defaultValue = "1") Integer pageIndex,
            @RequestParam(value = "page_size", defaultValue = "10") Integer pageSize){
        PageHelper.startPage(pageIndex, pageSize);
        List<Report> reportList = reportService.getAllUrgent();
        List<ReportVO> reportVOList;
        if(reportList == null){
            return ResponseUtil.fail();
        }else {
            reportVOList = ReportVO.getReportVOs(reportList);

            PageInfo pageInfo = ((Page)reportList).toPageInfo();
            pageInfo.setList(reportVOList);
            return ResponseUtil.ok(pageInfo);
        }

    }

    @ApiOperation("Ready, 根据id查询报告")
    @GetMapping("/report/{id}")
    public Object getReportById(@PathVariable Integer id){
        Report report = reportService.getReportById(id);
        if(report == null){
            return ResponseUtil.fail();
        }else {
            ReportVO reportVO = ReportVO.valueOf(report);
            return ResponseUtil.ok(reportVO);
        }
    }

    @ApiOperation("Ready, 根据no查询报告")
    @GetMapping("/report/no")
    public Object getReportByNo(@RequestParam String no){
        Report report = reportService.getReportByNo(no);
        if(report == null){
            return ResponseUtil.fail(401, "不存在的no");
        }else {
            ReportVO reportVO = ReportVO.valueOf(report);
            return ResponseUtil.ok(reportVO);
        }
    }

    @ApiOperation("Ready, 条件搜索报告")
    @PostMapping("/report/search")
    public Object searchReport(
            @RequestParam(value = "multiSources", defaultValue = "0") Integer multiSouces,
            @RequestBody SearchReportVO reportPageVO){
        Integer pageIndex = reportPageVO.getPageIndex();
        Integer pageSize = reportPageVO.getPageSize();
        Report report = reportPageVO.getReportVO().toReport();
        Date startTime = null;
        Date endTime = null;
        try {
            if(reportPageVO.getStartTime() != null
                && reportPageVO.getEndTime() != null){
                startTime = Date.valueOf(reportPageVO.getStartTime());
                endTime = Date.valueOf(reportPageVO.getEndTime());
            }
        }catch (Exception e){
            e.printStackTrace();
            return ResponseUtil.fail(401, "日期格式错误");
        }

        List<Report> reportList;
        List<ReportVO> reportVOList;
        if(multiSouces == 0){
            reportList = reportService.searchReports(report, startTime, endTime);
        }else if(multiSouces == 1){
            reportList = reportService.searchManyReportedReports(report, startTime, endTime);
        }else{
            return ResponseUtil.badArgumentValue();
        }

        /* do page split */
        Integer total = reportList.size();
        Integer pages = total / pageSize + 1;
        Integer start = (pageIndex - 1) * pageSize;
        if(start > total){
            start = total;
        }else if(start < 0){
            start = 0;
        }
        Integer end = (pageIndex) * pageSize;
        if(end > total){
            end = total;
        }
        reportList = reportList.subList(start,  end);
        reportVOList = ReportVO.getReportVOs(reportList);
        PageInfo pageInfo = new PageInfo(reportVOList);
        pageInfo.setPageNum(pageIndex);
        pageInfo.setPageSize(pageSize);
        pageInfo.setTotal(total);
        pageInfo.setPages(pages);

        return ResponseUtil.ok(pageInfo);


    }

    @ApiOperation("Ready, 增加报告")
    @PostMapping("/report")
    @Transactional(rollbackFor = Exception.class)
    public Object addReport(@RequestBody ReportVO reportVO){
        Report report = reportVO.toReport();
        String no = reportVO.getNo();
        Report tmpReport = reportService.getReportByNo(no);
        if(tmpReport != null){
            return ResponseUtil.fail(401, "编号不能重复");
        }

        int line = reportService.addReport(report);
        if(line == 1){
            return ResponseUtil.ok();
        }else{
            return ResponseUtil.fail();
        }
    }

    @ApiOperation("Ready, 删除报告")
    @DeleteMapping("/report/{id}")
    @Transactional(rollbackFor = Exception.class)
    public Object deleteReport(Integer id){
        Integer line = reportService.deleteReport(id);
        if(line == 1){
            return ResponseUtil.ok();
        }else{
            return ResponseUtil.fail(402, "不存在的id");
        }
    }

    @ApiOperation("修改报告")
    @PostMapping("/report/{id}")
    @Transactional(rollbackFor = Exception.class)
    public Object updateReport(@PathVariable Integer id, @RequestBody ReportVO reportVO){
        Report report = reportVO.toReport();
        report.setId(id);
        report = reportService.updateReport(report);
        if(report != null){
            return ResponseUtil.ok();
        }else{
            return ResponseUtil.fail(402, "不存在的id");
        }
    }

    @PostMapping("/report/import")
    public Object importExcel(@RequestParam MultipartFile excelFile) throws IOException{
        InputStream in = excelFile.getInputStream();
        XSSFWorkbook wb = new XSSFWorkbook(in);
        List<ReportVO> reportVOList = ExcelImporter.importExcel(wb);
        List<Report> reportList = new ArrayList<>();
        for(ReportVO reportVO: reportVOList){
            reportList.add(reportVO.toReport());
        }
        if(reportVOList == null){
            return ResponseUtil.fail(402, "excel格式错误");
        }
        reportService.importReports(reportList);
        return ResponseUtil.ok();
    }

    @GetMapping("/report/export")
    public void exportExcel(HttpServletResponse response,
                              @RequestParam(value = "type", defaultValue = "standard")String type) throws IOException, FileNotFoundException {
        Workbook wb;

        wb = reportService.toExcel(ExcelTypeConf.getStandardTemplate());


        response.setContentType("application/vnd.ms-excel;charset=UTF-8");
        response.setHeader(
                "Content-Disposition", "attachment;filename=" + new String("exported.xlsx".getBytes(), "iso-8859-1"));


        OutputStream out = response.getOutputStream();
        wb.write(out);
        wb.close();
    }


}
